package ynu.edu.elmspringboot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import ynu.edu.elmspringboot.interceptor.JwtInterceptor;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private JwtInterceptor jwtInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8081") // 允许的前端地址
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的方法
                .allowedHeaders("Authorization", "Content-Type", "Accept") // 明确允许的请求头
                .allowCredentials(true) // 是否允许携带凭据
                .maxAge(3600); // 缓存时间（秒）
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/UserController/login",
                        "/UserController/register",
                        "/UserController/getUserInfo",
                        "/UserController/getUserById",
                        "/**/options" // 确保 CORS 预检请求能通过
                )
                .excludePathPatterns("/static/**", "/css/**", "/js/**", "/images/**", "/favicon.ico", "/dist/**");
    }
}
